import os
import chardet
errors=[]
def encoding_get(filepath):
    # 读取文件内容
    with open(filepath, 'rb') as file:
        raw_data = file.read()

    # 检测编码
    result = chardet.detect(raw_data)
    encoding = result['encoding']
    return encoding
    # print(result)
    # 解码文本
    # decoded_text = raw_data.decode(encoding)
    # print(decoded_text)

def print_first_five_lines(file_path):
    try:
        count=0
        encoding=encoding_get(file_path)
        with open(file_path, 'r', encoding=encoding) as file:
            for i, line in enumerate(file, 1):
                count+=1
    except FileNotFoundError:
        st=f"文件 {file_path} 未找到或无法读取。"
        errors.append(st)
        print(st)
    except Exception as e:
        st=f"读取文件 {file_path} 时出错: {e}"
        errors.append(st)
        print(st)
    return count

# 在遍历文件夹时调用该函数
def traverse_directory_with_content(directory,form):
    count=0
    for filename in os.listdir(directory):
        count1=0
        file_path = os.path.join(directory, filename)
        if os.path.isfile(file_path):
            # 假设我们只处理文本文件
            if filename.endswith(form):  # 根据需要添加更多扩展名
                # print(f"处理文件: {filename}")
                count1=print_first_five_lines(file_path)
                print(f"处理文件: {filename}",f"-----{count1}")  # 打印一个空行以分隔不同文件的内容
        elif os.path.isdir(file_path):
            count1=traverse_directory_with_content(file_path,form)  # 递归处理子文件夹
        count += count1
    return count

# folder_path="D:\PythonLibrary\Python_Library\Python_Library\Project\\blender"
# 调用函数来遍历文件夹并处理文件内容
folder_path = r"D:\code\WeChat"
form=('.txt', '.csv', '.py', '.md','.js','.css','.html','.json')
count=traverse_directory_with_content(folder_path,form)
print(count)

print(errors)
# encoding_get("D:\PythonLibrary\Python_Library\Python_Library\Project\\blender\main.py")

